<!--
 * @Description: 
 * @Author: zhangwei
 * @Date: 2023-03-17 20:55:48
 * @LastEditTime: 2023-03-20 06:59:26
 * @LastEditors: zw 775925302@qq.com
-->
<!--
    表单的校验规则在每个表单项上面，不统一添加
-->

<script lang="tsx">

import { PropType, defineComponent, ref, unref } from 'vue'
import type { FormSchema } from "../../../types/lowcode"
import { formCmpMap } from '../../index'
import { Refresh, ArrowUp, Search, ArrowDown } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'

export default defineComponent({
    name: 'ZwSearch',
    props: {
        schema: {
            type: Object as PropType<FormSchema>,
            default: function () { return {} }
        },
    },
    emits: ["search"],
    setup(props, { emit }) {

        const formRef =  ref<FormInstance>()
        
        const search = () => {//查询操作，返回查询对象            
            unref(formRef)?.validate((isValid, fields) => {
                if (isValid) {                
                    emit('search')
                }else{
                    console.log("search valid error", fields)
                }
            })
        }

        //重置查询，如果有默认值则不可以重置
        const reset = () => {
            unref(formRef)?.resetFields()
            //重新添加默认值
            const { widgets = [],data} = unref(props.schema)
            widgets.forEach(item=>{
                if(item.defaultValue && item.defaultValue !=""){
                    data[item.key] = item.defaultValue;
                }
            })
            emit('search', props.schema.data)
        }

        // let expand = ref(true);
        //watch()
        const renderWrap = () => {
            const { widgets = [], data } = unref(props.schema)
            var cmps = widgets.filter((v) => !v.hidden).map(item => {
                const Com = formCmpMap[item.component as string] as ReturnType<typeof defineComponent>
                return <Com schema={item} vModel={data[item.key]}></Com>
            })
            cmps.push(
                <el-form-item>
                    <el-button type="primary" icon={Search} onClick={search}>查询</el-button>
                    <el-button icon={Refresh} onClick={reset} style="margin-left:16px">重置</el-button>
                    {/* <el-button text icon={expand.value ? ArrowDown : ArrowUp}>{expand.value ? "展开" : "收起"}</el-button> */}
                </el-form-item>
            )
            return cmps;
        }

        return () => (
            <el-form model={props.schema.data} {...props.schema.attrs} inline={true} ref={formRef}>
                {{
                    default: function () {
                        return renderWrap()
                    }
                }}
            </el-form>
        )
    }
})
</script>

<style lang="less" scoped></style>